package org.jeecg.modules.goodsorder.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.goods.service.IGoodsService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.service.IBalanceService;
import org.jeecg.modules.voucher.entity.Voucher;
import org.jeecg.modules.voucher.service.IVoucherService;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.goodsorder.entity.GoodsOrderDetail;
import org.jeecg.modules.goodsorder.entity.GoodsOrder;
import org.jeecg.modules.goodsorder.vo.GoodsOrderPage;
import org.jeecg.modules.goodsorder.service.IGoodsOrderService;
import org.jeecg.modules.goodsorder.service.IGoodsOrderDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 商品订单
 * @Author: jeecg-boot
 * @Date:   2024-07-11
 * @Version: V1.0
 */
@Api(tags="商品订单")
@RestController
@RequestMapping("/goodsorder/goodsOrder")
@Slf4j
public class GoodsOrderController {
	@Autowired
	private IGoodsOrderService goodsOrderService;
	@Autowired
	private IGoodsOrderDetailService goodsOrderDetailService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IBalanceService balanceService;
	@Autowired
	private IVoucherService voucherService;
	/**
	 * 分页列表查询
	 *
	 * @param goodsOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "商品订单-分页列表查询")
	@ApiOperation(value="商品订单-分页列表查询", notes="商品订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<GoodsOrder>> queryPageList(GoodsOrder goodsOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GoodsOrder> queryWrapper = QueryGenerator.initQueryWrapper(goodsOrder, req.getParameterMap());
		Page<GoodsOrder> page = new Page<GoodsOrder>(pageNo, pageSize);
		IPage<GoodsOrder> pageList = goodsOrderService.pageList(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param goodsOrderPage
	 * @return
	 */
	@AutoLog(value = "商品订单-添加")
	@ApiOperation(value="商品订单-添加", notes="商品订单-添加")
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody GoodsOrderPage goodsOrderPage) {
		GoodsOrder goodsOrder = new GoodsOrder();
		BeanUtils.copyProperties(goodsOrderPage, goodsOrder);
		goodsOrderService.saveMain(goodsOrder, goodsOrderPage.getGoodsOrderDetailList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param goodsOrderPage
	 * @return
	 */
	@AutoLog(value = "商品订单-编辑")
	@ApiOperation(value="商品订单-编辑", notes="商品订单-编辑")
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody GoodsOrderPage goodsOrderPage) {
		GoodsOrder goodsOrder = new GoodsOrder();
		BeanUtils.copyProperties(goodsOrderPage, goodsOrder);
		GoodsOrder goodsOrderEntity = goodsOrderService.getById(goodsOrder.getId());
		if(goodsOrderEntity==null) {
			return Result.error("未找到对应数据");
		}
		goodsOrderService.updateMain(goodsOrder, goodsOrderPage.getGoodsOrderDetailList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品订单-通过id删除")
	@ApiOperation(value="商品订单-通过id删除", notes="商品订单-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		goodsOrderService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商品订单-批量删除")
	@ApiOperation(value="商品订单-批量删除", notes="商品订单-批量删除")
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.goodsOrderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "商品订单-通过id查询")
	@ApiOperation(value="商品订单-通过id查询", notes="商品订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<GoodsOrder> queryById(@RequestParam(name="id",required=true) String id) {
		GoodsOrder goodsOrder = goodsOrderService.getById(id);
		if(goodsOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(goodsOrder);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "订单明细通过主表ID查询")
	@ApiOperation(value="订单明细主表ID查询", notes="订单明细-通主表ID查询")
	@GetMapping(value = "/queryGoodsOrderDetailByMainId")
	public Result<List<GoodsOrderDetail>> queryGoodsOrderDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<GoodsOrderDetail> goodsOrderDetailList = goodsOrderDetailService.selectByMainId(id);
		return Result.OK(goodsOrderDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param goodsOrder
    */
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GoodsOrder goodsOrder) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<GoodsOrder> queryWrapper = QueryGenerator.initQueryWrapper(goodsOrder, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<GoodsOrder> goodsOrderList = goodsOrderService.list(queryWrapper);

      // Step.3 组装pageList
      List<GoodsOrderPage> pageList = new ArrayList<GoodsOrderPage>();
      for (GoodsOrder main : goodsOrderList) {
          GoodsOrderPage vo = new GoodsOrderPage();
          BeanUtils.copyProperties(main, vo);
          List<GoodsOrderDetail> goodsOrderDetailList = goodsOrderDetailService.selectByMainId(main.getId());
          vo.setGoodsOrderDetailList(goodsOrderDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "商品订单列表");
      mv.addObject(NormalExcelConstants.CLASS, GoodsOrderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品订单数据", "导出人:"+sysUser.getRealname(), "商品订单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules:sr_goods_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<GoodsOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), GoodsOrderPage.class, params);
              for (GoodsOrderPage page : list) {
                  GoodsOrder po = new GoodsOrder();
                  BeanUtils.copyProperties(page, po);
                  goodsOrderService.saveMain(po, page.getGoodsOrderDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @SneakyThrows
	 @AutoLog(value = "商品订单-添加")
	 @ApiOperation(value="商品订单-添加", notes="商品订单-添加")
	 @PostMapping(value = "/doOrder")
	 public Result<GoodsOrder> doOrder(@RequestBody GoodsOrderPage orderPage) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 GoodsOrder order = new GoodsOrder();
		 BeanUtils.copyProperties(orderPage, order);
		 Float orderMoney = Float.valueOf(orderPage.getOrderMoney());
		 List<GoodsOrderDetail> detailList = orderPage.getGoodsOrderDetailList();
		 if(CollectionUtil.isNotEmpty(detailList)){
			 Map gMap = new HashMap();
			 for(GoodsOrderDetail detail : detailList){
				 String goodsId = detail.getGoodsId();
				 Integer cnt = detail.getCnt();
				 gMap.put(goodsId,cnt);
			 }
			 BigDecimal amt = goodsService.goodsPrice(gMap);
			 BigDecimal voucherAmt = new BigDecimal(0l);
			 String voucherId = orderPage.getVoucherId();
			 if(StringUtils.isNotBlank(voucherId)){
				 Voucher voucher = voucherService.getOne(new LambdaQueryWrapper<Voucher>()
						 .eq(Voucher::getId, voucherId)
						 .eq(Voucher::getSysUserId,sysUser.getId())
						 .eq(Voucher::getUseStatus,0)
						 .ge(Voucher::getEffectEndTime,new Date())
						 .le(Voucher::getEffectStartTime,new Date())
				 );
				 voucherAmt = voucher.getAmt();
			 }
			 if(amt.floatValue() - orderMoney - voucherAmt.floatValue() != 0){
				return Result.error("订单金额计算错误，请重试");
			 }
		 }

		 goodsOrderService.doOrder(sysUser,order,detailList);
		 return Result.OK(order);
	 }

	 @ApiOperation(value="订单支付使用余额", notes="订单支付使用余额")
	 @PostMapping(value = "/payorder")
	 public Result<String> payOrder(@RequestBody Map paramMap) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String orderNum = "" + paramMap.get("orderNum");
		 GoodsOrder order = goodsOrderService.getOne(new LambdaQueryWrapper<GoodsOrder>().eq(GoodsOrder::getSysUserId, sysUser.getId()).eq(GoodsOrder::getOrderNum, orderNum));
		 if (null == order) {
			 return Result.error("订单不存在，请确认");
		 }
		 Balance balance = balanceService.getOne(new LambdaQueryWrapper<Balance>().eq(Balance::getSysUserId, order.getSysUserId()));
		 if (null == balance) {
			 return Result.error("余额不足，请确认");
		 }
		 Float orderMoney = Float.valueOf(order.getOrderMoney());
		 Float money = balance.getBalance().floatValue();
		 if (money < orderMoney) {
			 return Result.error("余额不足，请确认");
		 }
		 goodsOrderService.payOrder(sysUser,order,balance);
		 return Result.OK();
	 }

	 @ApiOperation(value="小程序展示的订单列表", notes="小程序展示的订单列表")
	 @GetMapping(value = "/myorder")
	 public Result<IPage<GoodsOrder>> myOrder(@RequestParam List<String> status) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 LambdaQueryWrapper<GoodsOrder> queryWrapper = new LambdaQueryWrapper<GoodsOrder>()
				 .eq(GoodsOrder::getSysUserId,sysUser.getId())
				 .in(GoodsOrder::getOrderStatus,status)
				 .orderByDesc(GoodsOrder::getUpdateTime);

		 Page<GoodsOrder> page = new Page<GoodsOrder>(0, 99);
		 IPage<GoodsOrder> pageList = goodsOrderService.pageList(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @ApiOperation(value="小程序展示的订单详情", notes="小程序展示的订单详情")
	 @GetMapping(value = "/myorderdetail")
	 public Result<GoodsOrder> myOrderDetail(@RequestParam String orderNum) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 LambdaQueryWrapper<GoodsOrder> queryWrapper = new LambdaQueryWrapper<GoodsOrder>()
				 .eq(GoodsOrder::getSysUserId,sysUser.getId())
				 .eq(GoodsOrder::getOrderNum,orderNum);

		 GoodsOrder order = goodsOrderService.getOne(queryWrapper);
		 if(null != order){
			 List<GoodsOrderDetail> detailList = goodsOrderDetailService.selectByMainId(order.getId());
			 order.setDetailList(detailList);
		 }
		 return Result.OK(order);
	 }

	 @ApiOperation(value="取消未支付订单", notes="取消未支付订单")
	 @GetMapping(value = "/cancelorder")
	 public Result<String> cancelOrder(@RequestParam String orderNum) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 GoodsOrder order = goodsOrderService.getOne(new LambdaQueryWrapper<GoodsOrder>().eq(GoodsOrder::getSysUserId, sysUser.getId()).eq(GoodsOrder::getOrderNum, orderNum));
		 if (null == order) {
			 return Result.error("订单不存在，请确认");
		 }
		 if(!StringUtils.equals("0",""+ order.getOrderStatus())){
			 return Result.error("订单不能取消，请确认");
		 }
		 order.setOrderStatus("4");
		 if(StringUtils.isNotBlank(order.getVoucherId())){
			 Voucher voucher = voucherService.getById(order.getVoucherId());
			 voucher.setUseStatus(0);
			 voucherService.updateById(voucher);
		 }
		 goodsOrderService.updateById(order);
		 return Result.OK();
	 }

	 @ApiOperation(value="删除已取消订单", notes="删除已取消订单")
	 @GetMapping(value = "/delMyOrder")
	 public Result<String> delMyOrder(@RequestParam String orderNum) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 GoodsOrder order = goodsOrderService.getOne(new LambdaQueryWrapper<GoodsOrder>().eq(GoodsOrder::getSysUserId, sysUser.getId()).eq(GoodsOrder::getOrderNum, orderNum));
		 if (null == order) {
			 return Result.error("订单不存在，请确认");
		 }
		 if(!(StringUtils.equals("4",""+ order.getOrderStatus()) || StringUtils.equals("5","" + order.getOrderStatus()))){
			 return Result.error("订单不能删除，请确认");
		 }
		 goodsOrderService.delMain(order.getId());
		 return Result.OK();
	 }
}
